package com.igeek.health.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.igeek.health.constant.MessageConstant;
import com.igeek.health.entity.Ordersetting;
import com.igeek.health.result.Result;
import com.igeek.health.service.IOrdersettingService;
import com.igeek.health.utils.POIUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author fengqq
 * @Description TODO
 * @Date 2024/8/29  10:55
 */
@RestController
@RequestMapping("/admin/ordersetting")
@Slf4j
@Api(tags = "预约设置模块的控制层")
public class OrdersettingController {

    @Autowired
    private IOrdersettingService ordersettingService;

    @ApiOperation("模板下载")
    @GetMapping("/download")
    public void download(HttpServletResponse response){
        // 读取resources目下文件
        String templatePath = "classpath:template/ordersetting_template.xlsx";
        String filename = "ordersetting_template.xlsx";

        File file = null;
        try {
            file = ResourceUtils.getFile(templatePath);
        } catch (FileNotFoundException e) {
            log.warn("文件不存在 {}", filename);
            return;
        }

        if (file.isFile()) {
            byte[] fileNameBytes = filename.getBytes(StandardCharsets.UTF_8);
            filename = new String(fileNameBytes, 0, fileNameBytes.length, StandardCharsets.ISO_8859_1);

            response.reset();
            response.setContentType("application/force-download");
            response.setCharacterEncoding("utf-8");
            response.setContentLength((int) file.length());
            response.setHeader("Content-Disposition", "attachment;filename=" + filename);

            //从后台读取文件 通过response响应
            try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file))) {
                byte[] buff = new byte[1024];
                BufferedOutputStream os = new BufferedOutputStream(response.getOutputStream());
                int i;
                while ((i = bis.read(buff)) != -1) {
                    os.write(buff, 0, i);
                    os.flush();
                }
            } catch (IOException e) {
                log.error("下载出错 {}，错误原因 {}", filename, e.getMessage());
            }
        } else {
            log.warn("文件不存在 {}", filename);
        }
    }

    @ApiOperation("上传预约设置表")
    @PostMapping("/upload")
    public Result upload(MultipartFile  excelFile) throws IOException {
        //1.使用POI工具类 得到excel文件的数据
        List<String[]> list = POIUtils.readExcel(excelFile);
        //List<String[]> --> List<Ordersetting>
        List<Ordersetting> ordersettingList = list.stream().map(
                arr -> {
                    //arr[0] 2024.08.27 String-> Date
                    Date orderDate = DateUtil.parse(arr[0], "yyyy.MM.dd");
                    //arr[1] 400        String-> Integer
                    Integer number = Integer.valueOf(arr[1]);
                    Ordersetting ordersetting = new Ordersetting(orderDate,number);
                    return ordersetting;
                }
        ).collect(Collectors.toList());

        //2.更新预约设置表的数据
        boolean flag = ordersettingService.updateAll(ordersettingList);
        if(flag){
            return new Result(true, MessageConstant.IMPORT_ORDERSETTING_SUCCESS);
        }
        return new Result(false, MessageConstant.IMPORT_ORDERSETTING_FAIL);
    }

    @ApiOperation("根据年月查询预约设置信息")
    @GetMapping("/findDataByMonth/{year}/{month}")
    public Result findDataByMonth(
            @ApiParam("年") @PathVariable("year") Integer year,
            @ApiParam("月") @PathVariable("month") Integer month
    ){
        List<Map<String,Integer>> data = ordersettingService.findDataByMonth(year,month);
        if(CollUtil.isNotEmpty(data)){
            return new Result(true,MessageConstant.GET_ORDERSETTING_SUCCESS,data);
        }
        return new Result(false,MessageConstant.GET_ORDERSETTING_FAIL);
    }

    @ApiOperation("根据预约日期修改可预约数量")
    @PostMapping("/update")
    public Result update(@RequestBody  Ordersetting ordersetting){
        boolean flag = ordersettingService.updateOne(ordersetting);
        if(flag){
            return new Result(true,MessageConstant.ORDERSETTING_SUCCESS);
        }
        return new Result(false,MessageConstant.ORDERSETTING_FAIL);
    }

}
